package dataPO;

import java.util.ArrayList;

import server.Connector;
import system.ErrorProcessor;
import util.Message;

public class CourseRecordPO extends InfoPO {

	private static final long serialVersionUID = 1L;
	
	private String userID;
	private ArrayList<CoursePO> courses;

	public CourseRecordPO(String userID) {
		super(InfoPO.CourseRecordPO);
		this.userID = userID;
		this.refresh();
	}
	
	public void refresh() {
	    CoursePO[] temp = (CoursePO[]) Connector.getCourseRecord(userID).getItemList();
	    
	    courses.removeAll(null);
	    for(int i = 0; i < temp.length; i++) {
	        this.courses.add(temp[i]);
	    }
	}
	
	public CoursePO[] showMyCourses() {
        return courses.toArray(new CoursePO[courses.size()]);
    }
	
    public void addCourse(String courseID) {
        Message temp = Connector.getCourseRecord(userID);
        
        try {
            CoursePO info = ( (CoursePO[])temp.getItemList() )[0];
            
            this.courses.add(info);
            Connector.update(this);
            
        } catch(NullPointerException e) {
            ErrorProcessor.nullPointerProcess(temp);
        }        
    }
    
    public CoursePO getCourse(String courseID) {
        
        for(int i = 0; i < courses.size(); i++) {
            CoursePO temp = courses.get(i);
            if(temp.getCourseID().equals(courseID)) {
                return temp;
            }
        }
        return null;
    }

    public void deleteCourse(String courseID) {
        for(int i = 0; i < courses.size(); i++) {
            
            CoursePO temp = courses.get(i);
            if(temp.getCourseID().equals(courseID)) {
                this.courses.remove(i);
                this.courses.trimToSize();
                break;
            }
        }
        Connector.update(this);
    }
    
    public Message getGrade(String courseID) {
        Message info = Connector.getCourseStudentRecord(courseID);
        
        try {
            CourseStudentRecordPO temp = (CourseStudentRecordPO) info.getItem();
            return temp.getGrade(this.userID);
            
        } catch(NullPointerException e) {
            ErrorProcessor.nullPointerProcess(info);
        }
        return null;
    }

    @Override
    public String[][] toArray() {
        CoursePO[] temp = this.courses.toArray(new CoursePO[this.courses.size()]);
        String[][] result = new String[temp.length][];
        
        for(int i = 0; i < temp.length; i++) {
            result[i] = temp[i].toArray()[0];
        }
        return result;
    }

}
